

(function($) {
	
	$(document).ready(function() {
		xmlhttp=new XMLHttpRequest();
		$myblocks_content = $(".myblocks");
		$addBlocks = $(".addBlocks");
		$overlay = $(".overlay");
		$close = $(".close");
		$uploadCont = $(".uploadblocks-container");
		$deleteCont = $(".confirm-container");
		$addTag = $(".editTag");
		$step = $uploadCont.find('h3');
		$addTag.hide();
		$overlay.hide();
		$uploadCont.hide();
		
		$close.click(function() {
			closeUpload();
		});
		$addBlocks.hover(function() {
			$(this).css("opacity", "1.0");
			$(".addOverl").css("opacity", "1.0");
			$addTag.slideDown();
		}, function() {
			$(this).css("opacity", "0.5");
			$(".addOverl").css("opacity", "0.5");
			$addTag.slideUp();
		});
		
		$addBlocks.click(function() {
			uploadBlocks();
		});
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				$myblocks_content.append(xmlhttp.responseText);
				createMyBlocks();
				updateRecentTile();
				updateBlocksTile() 
				
				}
		}
																
								
		xmlhttp.open("GET","common/inc/user/getMyBlocks.php",true);
		xmlhttp.send();
		
		function updateRecentTile() {
			$('#new').find('div').empty();
			/*var comics = $('.myblocks').children('li');
			$com_images = comics.clone().children('img');
			$('#new').find('div').append($com_images.get(1));*/
			newTile=new XMLHttpRequest();
			
			newTile.onreadystatechange=function()
		{
			if (newTile.readyState==4 && newTile.status==200) {
				$('#new').find('div').append(newTile.responseText);
				
				
				}
		}
																
								
		newTile.open("GET","common/inc/user/getRecentTile.php",true);
		newTile.send();
		}
		
		function updateBlocksTile() {
			var comics = $('.myblocks').children('li');
			$com_images = comics.clone().children('img');
			var num = comics.length - 1;
			$('#blocks').find('div').empty();
			
			if(num < 1) {
				$('#blocks').find('h1').html('No Comics');
				$('#blocks').find('p').first().html('To add comics click here');
				}
			else {
				$('#blocks').find('h1').html(num + ' Comics');
				var max = 5;
				var i = 1;
				$comic_img = new Array();
				while(i < max) {
					if  ($com_images.get(i)) {
					$comic_img.push($com_images.get(i));
					i++;
					}
					else {
						break;
					}
				}
				$('#blocks').find('div').append($comic_img);
				}
				
				
		}
		function createMyBlocks() {
			deleteBlock = new XMLHttpRequest();
			
			$myblocks_content.children('li:not(:first-child)').each(function() {
			bindManageAndDelete($(this));
				//$(this).append($addTag)
			
			});
			
		}
		
		function bindManageAndDelete($item) {
			$title = $item.find('img').attr('title');
			$title = $title.replace(/\s/g, '_');
			$title = $title.replace(':', '_');
			$title = $title.replace('#', '');
			$mdoverl = "<div class='md'><a>Manage</a><a>Delete</a><a href=blocksreader.php?name="+ $title +" target='_blank'>Read</a><div>";
			$item.append($mdoverl);
			$item.find('div').hide();
			$item.find('div').css("width",$item.find('img').clientWidth);
			bindDelete($item.find('div').find('a:nth-child(2)'), $item);
			bindManage($item.find('div').find('a:first-child'));
			$item.click(function() {
				$(this).find('div').slideToggle();
			});
			//bindDelete($item)
		}
		

		
		function bindManage($item) {
			
			$manageContent = $('#manage-content');
			
			
			$item.click(function() {
				$img = $(this).parent().parent().find('img').clone();
				buildManageUI($manageContent, $img);
				showCustomWidget($manageContent,'600px', '600px', '20px', 'gray', closeManage) ;
			
			});
			
		
		}
		
		function buildManageUI($area, $img) {
			$area.find('aside').find('a').before($img);
			$area.find('aside').find('a').click(function() {
				
				managePages($area);
			});
			//Title
			$area.find('#title_val').html($img.attr('title'));
			$area.find('#title').attr('placeholder', $img.attr('title'))
			$area.find('#edit_title').click(function() {
				$area.find('#title_val').slideToggle();
				$area.find('#title').slideToggle();
				
				
			
			});
			//Synopsis
			$area.find('#edit_synopsis').click(function() {
				$area.find('#m_synopsis-val').slideToggle();
				$area.find('#m_synopsis').slideToggle();
			});
			
		}
		
		function managePages($area) {
			$area.find('#manage-main').slideUp();
			$area.find('#manage-pages').slideDown();
			uploadInit();
		
		}
		
		function closeManage() {
			 $('#manage-content').find('img').remove();
		}
		
		function bindDelete($item, $parent) {
		
			/*if (deleteBlock.readyState==3 || deleteBlock.readyState==2 || deleteBlock.readyState==1) {
				alert("Loading") ;
				}
			
			if (deleteBlock.readyState==4 && deleteBlock.status==200) {
				alert(deleteBlock.responseText) ;
				
				}*/
			$item.click(function() {
				$img = $(this).parent().parent().find('img').clone();
				
				var func = function() {
				var params = 'name='+$img.attr('title')+'&remove=true';
				deleteBlock.open('post',"upload-blocks.php",true);
				deleteBlock.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				deleteBlock.send(params);	
				
				$parent.remove();
				updateBlocksTile();
				updateRecentTile();
				
				}
				confirmWidget("Are you sure you want to delete?", func);
			});
		}
		
		
		function uploadBlocks() {
			
			showCustomWidget($('.uploadblocks-content'),'600px', '450px','20px', '#fff', closeUpload ) ; //Use clone here in the FUTURE!!
			upload=new XMLHttpRequest();
			upload_init=new XMLHttpRequest();
				upload.onreadystatechange=function()
		{
			if (upload.readyState==3 || upload.readyState==2 || upload.readyState==1) {
				processing() ;
				}
			if (upload.readyState==4 && upload.status==200) {
				thirdStep(upload.responseText) ;
				$added = upload.responseText;
				$myblocks_content.find($(".myblocks > li:first-child")).after($added);
				bindManageAndDelete($(".myblocks > li:nth-child(2)"));
				updateRecentTile();
				updateBlocksTile();
				}
		}
			$('#first_step').slideDown();
			
			
            $('#progress').css('width','0px');

			
			$('#first_step form').submit(function(){ 
				upload_init.open('post',"upload-pages.php",true);
				upload_init.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				upload_init.send(null);	return false; });
			
			$('#next_first').click(function () {	
			   //alert("hello!");
				secondStep();
			}
			);
			
			
			$('#upload').submit(function(){ return false; });
			
			$('#upload_2').submit(function(event){ 
					
				 event.preventDefault();
				
				var $form = $(this);
				// let's select and cache all the fields
				var $inputs = $form.find("input");
				// serialize the data in the form
				var serializedData = $form.serialize();													
								
				upload.open('post',"upload-blocks.php",true);
				upload.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				upload.send(serializedData);	
		
				
			
				
			});
	
			/*$('#upload_2').ajaxForm({ 
				beforeSubmit:function(){
					

				}, 
				success:function(){
					
				}, 
				error:function(){
					
				} }).submit();*/
		


			

			


		}
		
		function secondStep() {
			$title = $('#first_step input[type=text]').val();
			$synopsis = $('#first_step textarea').val();
				
			if ($title.length > 1 && $synopsis.length > 1) {
				$step.css('margin', '0px 210px');
				$step.html('Step2: Upload Pages');
				$('#first_step').slideUp();
				$('#second_step').slideDown();
				$('#progress').css('width','170px');
				$('#h_t').val($title);
				$('#h_s').val($synopsis);
				$('#next_second').css("opacity","0.5");

				
			}
			uploadInit();
		
		}
		
		function thirdStep($result) {
			$step.css('margin', '0px 410px');
			$step.html('Step3: Done!');
			$('#progress').css('width','330px');
			$('#processing').slideUp();
			$('#third_step').slideDown();
			$('#third_step').append($result)
			$('#third_step').append("<div><h2>"+ $('#h_t').val() +"</h2> \
			<h3>has been added to your block list! To publish choose publish, to manage choose manage. </h3>\
			\
			<a id='publish'>Publish</a>\
			<a id='manage'>Manage</a>\
			<a class='button'>Close</a>\
			</div>");
			
			$('#third_step').find('.button').click(function() {
			closeUpload();
			$parent = $('.widget-container');
			$parent.find('.overlay').hide();
			$parent.find('.close').hide();
			$parent.find('.custom-widget').slideUp();
			
			
			
			;});
			
			$('#third_step').find('#manage').click(function() {
				$('#third_step').find('.button').click();
				$(".myblocks > li:nth-child(2)").find('a:first-child').click();
			
			});
		}
		
		function processing() {
		
			$('#second_step').slideUp();
			$('#processing').slideDown();
		}
		
		function resetForm($form) {
			$form.find('input:text, input:password, input:file, select, textarea').val('');
			$form.find('input:radio, input:checkbox')
         .removeAttr('checked').removeAttr('selected');
		}
		
		function closeUpload() {
			$step.css('margin', '0px 40px');
			$step.html('Step1: Block Details');
			resetForm($("#upload"));
			resetForm($("#upload_2"));
			resetForm($('#first_step form'));
			$('#upload ul').empty();
			$('#second_step').slideUp();
			$('#first_step').slideUp();
			$('#third_step').empty();
			$('#third_step').slideUp();
			$('#processing').slideUp();


			
		}
	
	});
    
})(jQuery);